<template>
  <div class="login">
    <el-form class="form" :rules="rules" :model="form" ref="form">
      <h3>Login</h3>
      <el-form-item label="用户名" label-width="80px" prop="userName">
        <el-input
            class="item"
            required="required"
            v-model="form.userName"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" label-width="80px" prop="password">
        <el-input
            class="item"
            required="required"
            v-model="form.password"
            show-password
        ></el-input>
      </el-form-item>
      <el-form-item label="验证码" label-width="80px" prop="code">
        <el-input class="item" required="required" v-model="form.code">
          <template v-slot:suffix>
            <SIdentify
                :identifyCode="identifyCode"
                @click="refreshCode"
                contentHeight="30"
                :contentWidth="90"
                class="code"
            ></SIdentify>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit(form)">登录</el-button>
        <router-link to="/register">没有账号?注册一个</router-link>
        <el-button @click="resetForm('form')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import SIdentify from "../components/identify.vue";
import {login, lookCurrentUser} from "../api/user";
import {ElMessage} from "element-plus";
import jwtDecode from "jwt-decode";

export default {
  components: {
    SIdentify,
  },
  data() {
    return {
      currentUser: {},
      isAdmin: false,
      form: {
        userName: "root",
        password: "12345678",
      },
      //随机数仓库
      identifyCodes: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
      //验证码
      identifyCode: "",
      rules: {
        userName: [
          {required: true, message: "用户名不得为空!", trigger: "blur"},
        ],
        password: [
          {required: true, message: "密码不得为空!", trigger: "blur"},
          {
            min: 6,
            max: 12,
            message: "长度在 6 到 12 个字符",
            trigger: "blur",
          },
        ],
        code: [
          {required: true, message: "验证码不得为空!", trigger: "blur"},
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value !== this.identifyCode) {
                callback(new Error("验证码错误!"));
                this.refreshCode();
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.refreshCode();
  },
  methods: {
    onSubmit(user) {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          login(user.userName, user.password).then((req) => {
            if (req.data.success) {
              //获取token
              var token = req.data.data;
              var user = jwtDecode(token).user;
              sessionStorage.setItem("token", token);
              this.lookCurrentUser(user);
              setTimeout(() => {
                console.log(sessionStorage.getItem("per"));
                if (sessionStorage.getItem("per")[0] === "N") {
                  ElMessage({
                    message: `对不起,你无权访问此系统!`,
                    type: "error",
                    showClose: true,
                  });
                  return;
                }
                ElMessage({
                  message: "登录成功!",
                  type: "success",
                  showClose: true,
                });
                sessionStorage.setItem("user", user);
                this.$router.push({name: "page"});
              }, 500);
            } else {
              ElMessage({
                message: `${req.data.message}`,
                type: "error",
                showClose: true,
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    //获取当前用户
    lookCurrentUser(uid) {
      lookCurrentUser(uid).then((req) => {
        this.currentUser = req.data.data;
        sessionStorage.setItem("per", this.currentUser.permissions);
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    },
    refreshCode() {
      this.identifyCode = "";
      this.makeCode(this.identifyCodes, 4);
    },
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode +=
            this.identifyCodes[this.randomNum(0, this.identifyCodes.length)];
      }
    },
  },
};
</script>

<style lang="less" scoped>
.login {
  background: url("../assets/1.jpg") no-repeat;
  background-size: 100%;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;

  .form {
    margin-top: 15%;
    border-radius: 20px;
    width: 30%;
    margin-bottom: 20vh;
    background-color: white;
    // border-radius: 2px;
    padding: 1% 3%;

    .item {
      width: 75%;
    }

    .code {
      height: 30px;
    }

    .el-button {
      margin-left: 6%;
    }

    a {
      line-height: 20px;
      color: #67c23a;
      margin-left: 6%;
    }

    h3 {
      text-align: center;
    }
  }
}
</style>